/*
 * {comment of class}
 *
 * @author (C) <a href="http://www.carfield.com.hk">Carfield Yim</a>, 2004
 */
package hk.com.carfield.content;

import hk.com.carfield.core.Config;
import hk.com.carfield.util.StringUtil;
import hk.com.carfield.web.Request;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;

public final class Code implements Content, Editable {
	public String process(final Request req) throws IOException {
		// TODO return syntax highlight editor
		if (req != null) {
			FileUtils.writeStringToFile(file, req.getParameter("code"), "UTF-8");
		}
		return getContent();
	}

	private final Config config;

	public Code(final Config config, final File file) {
		super();
		this.config = config;
		this.file = file;
	}

	private final File file;

	public String getContent() throws IOException {
		final InputStream is = new FileInputStream(file);
		try {
			return "<TEXTAREA name=\"code\" class=\"" + StringUtil.getExtensions(file.getName())
					+ "\" rows=\"16\" cols=\"100\">" + StringEscapeUtils.escapeHtml(IOUtils.toString(is, "UTF-8"))
					+ "</TEXTAREA><br>";
		} finally {
			is.close();
		}
	}

	public String getThumbnail() {
		// TODO add default icon for difference type... should get through
		// servlet so that one jar is ok
		return null;
	}

	// TODO check how to extract metadata (signature??) from code
}
